package com.puman.beautyfarmcounselor.ui.home.adpter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.home.MemberVipFragment;
import com.puman.beautyfarmcounselor.ui.home.model.TaskVipMember;
import com.puman.beautyfarmcounselor.ui.task.MemberFragment;
import com.puman.beautyfarmcounselor.ui.task.model.TaskMember;
import com.puman.beautyfarmcounselor.ui.task.view.SlideView;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.PublicData;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Curry on 2015/7/20.
 */
public class MemberVipListsAdapter extends BaseAdapter {

    private Context context;
    private TaskVipMember taskVipMember;
    private Map<Integer, SlideView> recordMap = new HashMap<Integer, SlideView>();
    MemberVipFragment memberFragment;
    int allPosition = 0;

    public MemberVipListsAdapter(MemberVipFragment memberFragment, TaskVipMember taskVipMember) {
        this.memberFragment = memberFragment;
        this.taskVipMember = taskVipMember;
    }

    @Override
    public int getCount() {
        return taskVipMember.getData().getFollow_list().size();
    }

    @Override
    public Object getItem(int position) {
        return taskVipMember.getData().getFollow_list().get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (memberFragment.feedbackMsg) {
            holder.msgImg.setVisibility(View.VISIBLE);
            holder.msgImg.setTag(position);
            holder.msgImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int posi = (int) v.getTag();
                    showNoticy(posi, 2);

                }
            });

        }
        if (memberFragment.feedbackTel) {
            holder.telImg.setVisibility(View.VISIBLE);
            holder.telImg.setTag(position);
            holder.telImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    showNoticy(position, 1);
                    allPosition = position;
                }
            });
        }

        if (taskVipMember.getData().getFollow_list().get(position).getStatus() == 1) {
            holder.headImg.setImageDrawable(memberFragment.getActivity().getResources().getDrawable(R.drawable.customer_user_unselect));
        }
        holder.name.setText(taskVipMember.getData().getFollow_list().get(position).getName());


        return convertView;
    }

    public static final int DELAY_SHOW = 0x11;

    Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case DELAY_SHOW:
                    showAlertInfo();
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    Handler handler = new Handler(callback);

    private void sendMessageDelay(int what, int delayMillis) {
        Message msg = new Message();
        msg.what = what;
        handler.sendMessageDelayed(msg, delayMillis);

    }
    private AlertDialog alertDialog;
    private void showNoticy(int position, final int showFlag) {
        int posi = position;
        alertDialog = new AlertDialog.Builder(MainActivity.getInstace()).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.info_dialog);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// 弹出键盘
        TextView info = (TextView) window.findViewById(R.id.call_state);
        if (showFlag == 1){
            MethedUtil.UtilLog("showFlag:"+showFlag);
            info.setText(R.string.call_info);
        }else{
            MethedUtil.UtilLog("showFlag:"+showFlag);
            info.setText(R.string.send_msg_info);
        }
        RelativeLayout sureBtn = (RelativeLayout) window.findViewById(R.id.sure_btn_layout);
        RelativeLayout cloWin = (RelativeLayout) window.findViewById(R.id.close_win);

        sureBtn.setTag(posi);
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                int position = (int) v.getTag();
                if (showFlag == 1) {

                    Intent intent = new Intent(Intent.ACTION_CALL, // 创建一个意图
                            Uri.parse("tel:"
                                    + taskVipMember.getData().getFollow_list().get(position).getMobile()));
                    MainActivity.getInstace().startActivity(intent);// 开始意图(及拨打电话)
                    sendMessageDelay(DELAY_SHOW, 1500);
                } else {
                    String phone_number = taskVipMember.getData().getFollow_list().get(position).getMobile().trim();
                    String sms_content = memberFragment.messageModelContent;
                    Uri uri = Uri.parse("smsto:" + phone_number);
                    Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                    sendIntent.putExtra("sms_body", sms_content);
                    MainActivity.getInstace().startActivity(sendIntent);
                }

            }
        });

        cloWin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    private AlertDialog feedDlg;
    private String feedType = "1";//1:成功沟通，2:无情挂断，3:无人接听，4:电话错误

    public void showAlertInfo() {
        feedDlg = new AlertDialog.Builder(MainActivity.getInstace()).create();
        feedDlg.show();
        Window window = feedDlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.task_submit_dialog);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// 弹出键盘
        // 为确认按钮添加事件,执行退出应用操作
        TextView infoTitle = (TextView) window
                .findViewById(R.id.location_alert_text); // 提示标题
        final EditText infoDetail = (EditText) window
                .findViewById(R.id.info_advice); // 提示详情
        RelativeLayout closeWin = (RelativeLayout) window
                .findViewById(R.id.close_win);
        closeWin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                feedDlg.dismiss();
            }
        });
        infoTitle.setText("沟通情况");
        final ImageView itemImage1 = (ImageView) window
                .findViewById(R.id.select_item_image1);
        final ImageView itemImage2 = (ImageView) window
                .findViewById(R.id.select_item_image2);
        final ImageView itemImage3 = (ImageView) window
                .findViewById(R.id.select_item_image3);
        final ImageView itemImage4 = (ImageView) window
                .findViewById(R.id.select_item_image4);
        final TextView itemInfo1 = (TextView) window
                .findViewById(R.id.item1_info);
        final TextView itemInfo2 = (TextView) window
                .findViewById(R.id.item2_info);
        final TextView itemInfo3 = (TextView) window
                .findViewById(R.id.item3_info);
        final TextView itemInfo4 = (TextView) window
                .findViewById(R.id.item4_info);
        RelativeLayout itemLayout1 = (RelativeLayout) window
                .findViewById(R.id.select_item1);
        RelativeLayout itemLayout2 = (RelativeLayout) window
                .findViewById(R.id.select_item2);
        RelativeLayout itemLayout3 = (RelativeLayout) window
                .findViewById(R.id.select_item3);
        RelativeLayout itemLayout4 = (RelativeLayout) window
                .findViewById(R.id.select_item4);
        itemImage1.setVisibility(View.VISIBLE);
        itemLayout1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                feedType = "1";
                itemImage1.setVisibility(View.VISIBLE);
                itemImage2.setVisibility(View.GONE);
                itemImage3.setVisibility(View.GONE);
                itemImage4.setVisibility(View.GONE);
                itemInfo1.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.black));
                itemInfo2.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo3.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo4.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));

            }
        });
        itemLayout2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                feedType = "2";
                itemImage1.setVisibility(View.GONE);
                itemImage2.setVisibility(View.VISIBLE);
                itemImage3.setVisibility(View.GONE);
                itemImage4.setVisibility(View.GONE);
                itemInfo1.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo2.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.black));
                itemInfo3.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo4.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));

            }
        });
        itemLayout3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                feedType = "3";
                itemImage1.setVisibility(View.GONE);
                itemImage2.setVisibility(View.GONE);
                itemImage3.setVisibility(View.VISIBLE);
                itemImage4.setVisibility(View.GONE);
                itemInfo1.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo2.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo3.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.black));
                itemInfo4.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));

            }
        });
        itemLayout4.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                feedType = "4";
                itemImage1.setVisibility(View.GONE);
                itemImage2.setVisibility(View.GONE);
                itemImage3.setVisibility(View.GONE);
                itemImage4.setVisibility(View.VISIBLE);
                itemInfo1.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo2.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo3.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.gray));
                itemInfo4.setTextColor(memberFragment.getActivity().getResources().getColor(
                        R.color.black));
            }
        });

        TextView sureBtn = (TextView) window.findViewById(R.id.sure_btn);
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feedDlg.dismiss();
                submitFeed();
            }
        });

    }

    XTHttp xtHttp = new XTHttp();
    String url = "";
    String param = "";

    private void submitFeed() {
        int type;
        if (memberFragment.feedbackTel) {
            type = 1;
        } else {
            type = 2;
        }
        param = "emp_id=" + GlobalData.counselor.getData().getEmployee_id() +
                "&target_id=" + taskVipMember.getData().getFollow_list().get(allPosition).getTarget_id() +
                "&tel_status=" + feedType +
                "&type=" + type;
        url = RequestAddr.feedNote + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    PublicData publicData;

    private void dealData(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            publicData = mapper.readValue(object.toString(), PublicData.class);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (publicData == null) {
            return;
        }
        MethedUtil.UtilToast(memberFragment.getActivity(), publicData.getMsg());

    }


    public static class ViewHolder {
        public TextView name;
        public ImageView telImg;
        public ImageView msgImg;
        public ImageView headImg;
        public ViewGroup deleteHolder;
        public RelativeLayout itemLayout;

        ViewHolder(View v) {
            name = (TextView) v.findViewById(R.id.member_list_name);
            telImg = (ImageView) v.findViewById(R.id.memeber_list_tel);
            msgImg = (ImageView) v.findViewById(R.id.memeber_list_message);
            headImg = (ImageView) v.findViewById(R.id.member_list_headImg);
            itemLayout = (RelativeLayout) v.findViewById(R.id.member_item_layout);
        }

    }


}
